package cn.yl.course.server.service.impl;

import cn.yl.api.server.result.Constants;
import cn.yl.api.server.util.redis.RedisKeyUtils;
import cn.yl.api.server.util.redis.RedisUtils;
import cn.yl.course.server.entity.ActivityCourse;
import cn.yl.course.server.entity.Course;
import cn.yl.course.server.entity.dto.CourseDto;
import cn.yl.course.server.entity.dto.CourseLessonDto;
import cn.yl.course.server.entity.dto.CourseSectionDto;
import cn.yl.course.server.mapper.CourseLessonMapper;
import cn.yl.course.server.mapper.CourseMapper;
import cn.yl.course.server.service.ActivityCourseService;
import cn.yl.course.server.service.CourseService;
import cn.yl.course.server.service.TeacherService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author yl
 * @since 2022-04-22
 */
@Slf4j
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private RedisUtils redisUtils;

    private final ActivityCourseService activityCourseService;
    private final CourseLessonMapper courseLessonMapper;

    public CourseServiceImpl(CourseLessonMapper courseLessonMapper, ActivityCourseService activityCourseService) {
        this.courseLessonMapper = courseLessonMapper;
        this.activityCourseService = activityCourseService;
    }

    @Override
    public List<CourseDto> getAllCourse() {
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.KEY_COURSE_TREE);
        Object o = redisUtils.get(key);
        ArrayList<CourseDto> allCourse = null;
        if (o == null) {
            synchronized (this) {
                o = redisUtils.get(key);
                if (o == null) {
                    QueryWrapper<CourseDto> wrapper = new QueryWrapper<>();
                    LocalDate now = LocalDate.now();
                    wrapper.orderByAsc("c.sort_num");
                    wrapper.orderByDesc("amount", "ac.create_time");
                    allCourse = baseMapper.getAllCourse(wrapper);
                    allCourse.forEach(
                            courseDto -> {
                                courseDto.getCourseSections().forEach(courseSectionDto ->
                                        courseSectionDto.setCourseLessons(courseLessonMapper.getCourseLessonDtoList(courseSectionDto.getId()))
                                );
                            }
                    );
                    log.info("存入redis");
                    setRedisData(allCourse);
                } else {
                    allCourse = JSON.parseObject(o.toString(), ArrayList.class);
                }
            }
        } else {
            log.info("访问redis");
            allCourse = JSON.parseObject(o.toString(), ArrayList.class);
        }
        return allCourse;
    }

    @Override
    public List<CourseDto> getByIds(ArrayList ids) {
//        ArrayList<CourseDto> courseDtoArrayList = new ArrayList<>();
//        ArrayList<Integer> courseIds = new ArrayList<>();
//        while (ids.contains("=")) {
//            if (!ids.contains("&")) {
//                courseIds.add(Integer.parseInt(ids.substring(ids.indexOf("=") + 1)));
//                break;
//            }
//            courseIds.add(Integer.parseInt(ids.substring(ids.indexOf("=") + 1, ids.indexOf("&"))));
//            ids = ids.substring(ids.indexOf("&") + 1);
//        }
//        String[] courseIds = ids.split(",");
        QueryWrapper<CourseDto> wrapper = new QueryWrapper<>();
        wrapper.in("c.id", ids);
        ArrayList<CourseDto> allCourse = baseMapper.getAllCourse(wrapper);
        allCourse.forEach(
                courseDto -> {
                    courseDto.getCourseSections().forEach(courseSectionDto ->
                            courseSectionDto.setCourseLessons(courseLessonMapper.getCourseLessonDtoList(courseSectionDto.getId()))
                    );
                }
        );
        return allCourse;
    }

    @Override
    public void updateSalesAndRedis(Integer courseId) {
        Course course = this.getById(courseId);
        course.setSales(course.getSales()+1);
        this.updateById(course);
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.KEY_COURSE_TREE);
        redisUtils.delete(key);
    }


    private void setRedisData(List<CourseDto> list) {
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.KEY_COURSE_TREE);
        String jsonString = JSON.toJSONString(list);
        // 第三个参数不写，就不设置时间，一般推荐设置时间
        redisUtils.putValue(key, jsonString, Constants.Duration.MINUTE);
    }
}
